echo "now, begin to build project!"

SHELL_NAME="=========================== deploy.sh is start！==========================="
#项目代码部署的地方
#需要在webhook通知此脚本之前在该目录下执行 git clone 相关的指令 这部分比较简单，暂时先忽略
PROJECT_DIR="/Users/linhao/IdeaProjects/qiyu-mall/mall-user/"
INPUT_PARAM=""

echo $SHELL_NAME

# 切换到当前目录文件夹下边查看信息
turn_to_project_dir(){
  cd $PROJECT_DIR
  ls
}

echo_param(){
  INPUT_PARAM=$1
  echo $INPUT_PARAM
}

# 检查当前是否是空目录
init(){
    # if语法 [ ] 之间要有空格 否则语法异常
   	if [ ! -d $PROJECT_DIR ]; then
   	echo "$PROJECT_DIR not exists"
   	else 
   	echo "$PROJECT_DIR existed"  
    mvn clean package

   	start_build_provider
   	start_build_consumer
   	fi
}

#启动provider服务
start_build_provider(){
   cd $PROJECT_DIR 
   #这里应该用`符号 否则便利的时候会有问题
   provider_name=`ls | grep *-provider`
   for file in $provider_name
   do
     cd $file
     cd "./target/"
     pwd
     nohup  java -jar -Xms128m -Xmx128m mall-user-provider.jar > mall-provider-log.file 2>&1 &
     echo "===================== provider is starting!! ====================="
   done
}


#启动消费端服务
start_build_consumer(){
   #如果端口没有占用的话进入等待阶段 上限为400s
    i=1
    while [ $i -lt 100 ]
    do
        #暂时写死端口号，通过监听端口号判断服务是否已经启动
        is_provider_start=`netstat -an | grep "18081" | awk '$1 like "tcp" && $NF == "LISTEN" {print $0}' | wc -l`
        echo $is_provider_start  
        if [ $is_provider_start -eq 0 ]; then
          echo "------------- provider正在启动中 ------------"
        else
          break  
        fi
          
        sleep 4s
        
        ((i++))
    done

    if [ i -lt 100 ]; then
      echo "xxxxxxxxxxxxxxxxx -- provider启动超时 -- xxxxxxxxxxxxxxxxx"
    else
      run_build_consumer  
    fi 
}

#这里才开始启动消费端程序

run_build_consumer(){
  #如果端口被占用的话要怎么怎么样
      echo "provider服务运行正常!"
      cd $PROJECT_DIR 

      #这里应该用符号 否则便利的时候会有问题
      consumer_name=`ls | grep *-consumer`
      for file in $consumer_name
        do
          cd $file
          cd "./target/"
          pwd
          nohup  java -jar -Xms128m -Xmx128m mall-user-consumer.jar > mall-consumer-log.file 2>&1 &
          echo "===================== consumer is starting!! ====================="
      done
}


main(){
  turn_to_project_dir
  init	
  
}

main
